# coding=utf-8
from db_model import DbModel


class Field(object):
    def __init__(self, **kwargs):
        self.name = kwargs.get('name', None)
        self.max_length = kwargs.get('max_length', 2048)
        self.null_able = kwargs.get('null', False)
        self.default = kwargs.get('default', None)


class CharField(Field):
    def __init__(self, **kwargs):
        if 'default' not in kwargs:
            kwargs['default'] = ''
        super(CharField, self).__init__(**kwargs)


class IntegerField(Field):
    def __init__(self, **kwargs):
        if 'default' not in kwargs:
            kwargs['default'] = 0
        super(IntegerField, self).__init__(**kwargs)


class FloatField(Field):
    def __init__(self, **kwargs):
        if 'default' not in kwargs:
            kwargs['default'] = 0.0
        super(FloatField, self).__init__(**kwargs)


class TextField(Field):
    def __init__(self, **kwargs):
        if 'default' not in kwargs:
            kwargs['default'] = ''
        super(TextField, self).__init__(**kwargs)


class ModelMetaClass(type):
    """model类的元类"""

    def __new__(mcs, name, bases, attrs):
        if name == 'Model':
            return type.__new__(mcs, name, bases, attrs)
        if not hasattr(mcs, 'subclasses'):
            mcs.subclasses = {}
        if name not in mcs.subclasses:
            mcs.subclasses[name] = name
        else:
            print 'redefine class: %s' % name

        print 'scan orm %s' % name
        mappings = {}
        for k, v in attrs.iteritems():
            if isinstance(v, Field):
                if not v.name:
                    v.name = k
                mappings[k] = v

        for k in mappings.iterkeys():
            attrs.pop(k)
        if '__table__' not in attrs:
            attrs['__table__'] = name.lower()
        attrs['__mappings__'] = mappings
        return type.__new__(mcs, name, bases, attrs)


class Model(dict):
    """"model基类，实现orm的功能"""

    __metaclass__ = ModelMetaClass

    def __init__(self, **kwargs):
        super(Model, self).__init__(**kwargs)

    def __getattr__(self, item):
        try:
            return self[item]
        except KeyError:
            raise AttributeError("object has no attribute of %s" % item)

    def __setattr__(self, key, value):
        self[key] = value

    @classmethod
    def get(cls, *args, **kwargs):
        """查找记录"""
        return DbModel.select_one(cls.__table__, kwargs.keys(), *kwargs.values())

    @classmethod
    def find(cls, *args, **kwargs):
        """查找记录集"""
        return DbModel.select(cls.__table__, kwargs.keys(), *kwargs.values())

    def save(self):
        """新加保存"""
        params = {}
        for k, v in self.__mappings__.iteritems():
            if not hasattr(self, k):
                setattr(self, k, v.default)
            params[v.name] = getattr(self, k)
        DbModel.save(self.__table__, params.keys(), *params.values())
        return self

if __name__ == '__main__':
    # print Model.save(level_id=5, level='六级')
    pass
